package framework.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 类资源加载
 */
public class ClassResourceUtil {

    /**
     * 检索资源
     *
     * @param pattern
     * @return
     * @throws IOException
     */
    public static List<String> searchResources(String pattern) throws IOException {
        return searchResources(pattern, null);
    }

    /**
     * 检索资源
     *
     * @param pattern
     * @param dirname 需要去除的目录名称
     * @return
     * @throws IOException
     */
    public static List<String> searchResources(String pattern, String dirname) throws IOException {
        List<String> list = new ArrayList<>();

        //
        String p0 = null;
        if (StringUtils.isNotBlank(dirname)) {
            URL dirPath = ClassLoader.getSystemResource(dirname);
            if (dirPath == null) {
                throw new IOException("Not found dir name " + dirname);
            }
            p0 = dirPath.getPath();
        }

        //
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:" + pattern);

        //
        if (p0 == null) {
            for (Resource resource : resources) {
                list.add(resource.getURL().getPath());
            }
        } else {
            for (Resource resource : resources) {
                String p1 = resource.getURL().getPath();
                if (p1.startsWith(p0)) {
                    list.add(p1.substring(p0.length()));
                }
            }
        }

        //
        return list;
    }

}
